package com.qf.conf;

import com.alibaba.fastjson.JSON;
import com.qf.consts.Code;
import com.qf.pojo.R;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;

@Configuration
public class SecutiryConfig extends WebSecurityConfigurerAdapter {

    //注入一个密码加密器
    @Bean
    public PasswordEncoder passwordEncoder(){
        //明文的密码加密器（对密码不进行任何的加密动作）
//        return NoOpPasswordEncoder.getInstance();

        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        super.configure(auth);
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        super.configure(web);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        //配置跨域解决方案
        http.cors().configurationSource(corsCS());

        http.authorizeRequests()
                //访问/user/findAll资源需要登录，不需要权限
                .antMatchers("/user/findAll").authenticated()
                //访问/user/findAll资源需要P1的权限
                .antMatchers("/user/findAll").hasAuthority("P1")
                //允许所有资源的访问（不需要登录&权限校验）
                .antMatchers("/**").permitAll();

        http.exceptionHandling()
                //设置需要登录，但是没有登录的监听
                .authenticationEntryPoint(new AuthenticationEntryPoint() {
                    //当我们访问一些需要登录认证的资源，但是当前却没有登录时，会触发这个方法的调用
                    @Override
                    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
                        //System.out.println("当前未登录...");
                        R r = R.error("请先登录").putCode(Code.NO_LOGIN);
                        String json = JSON.toJSONString(r);

                        response.setContentType("application/json;charset=utf-8");
                        response.getWriter().write(json);
                    }
                })
                //设置需要权限，但是没有权限的监听
                .accessDeniedHandler(new AccessDeniedHandler() {
                    //当我们访问一些需要权限的资源，但是当前却没有权限时，会触发这个方法的调用
                    @Override
                    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
                        R r = R.error("无权访问").putCode(Code.NO_AUTH);
                        String json = JSON.toJSONString(r);

                        response.setContentType("application/json;charset=utf-8");
                        response.getWriter().write(json);
                    }
                })
        ;

        //禁用SpringSecurity的跨站伪造攻击功能
        http.csrf().disable();

        //启用UsernamePasswordAuthenticationFilter过滤器（使用JWT方案时，这个地方需要改造）
        http.formLogin()
                //成功登录的监听器
                .successHandler(new SuccessLoginHandler())
                //登录失败的监听器
                .failureHandler(new FailLoginHandler())
                //允许任何资源发起登录访问
                .permitAll();
    }

    /**
     * 配置同源策略解决方案
     * @return
     */
    private CorsConfigurationSource corsCS() {
        UrlBasedCorsConfigurationSource ubcs = new UrlBasedCorsConfigurationSource();
        CorsConfiguration corsC = new CorsConfiguration();

        //允许所有来源的访问
        corsC.setAllowedOrigins(Arrays.asList("http://localhost"));
        //允许所有请求方式的访问（比如：post、get、put、delete...）
        corsC.setAllowedMethods(Arrays.asList("*"));
        //允许任意请求头信息的携带（不包含cookie）
        corsC.setAllowedHeaders(Arrays.asList("*"));
        //允许请求携带cookie（如果这个值设置为true，Origins就不能用*了，需要指明具体的origin来源，比如： http://localhost,....）
        corsC.setAllowCredentials(true);
        //允许响应时携带任意名称的响应头
        corsC.setExposedHeaders(Arrays.asList("*"));

        //访问当前服务器的所有资源，都采用这一套同源策略方案
        ubcs.registerCorsConfiguration("/**",corsC);
        return ubcs;
    }
}
